package com.eat.fish_service.netty_client.handler;

import com.eat.fish_service.entity.Dao.IpAndPort;
import com.eat.fish_service.netty_client.ManageConnections;
import com.eat.fish_service.netty_client.Message;
import com.eat.fish_service.service.IpAndPortService;
import com.eat.fish_service.utils.GetBeanUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CZF
 * @create 2022-04-05 20:12
 *
 * 消息入站处理器
 * 客户端数据使用的handler
 */
@Slf4j
public class MessageHandler extends SimpleChannelInboundHandler<Message> {

    //从spring容器中取bean
    IpAndPortService ipAndPortService = GetBeanUtils.getBean(IpAndPortService.class);

    //数据处理
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {

    }

    //channel断开连接处理方法
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //根据断开的channel删除map中对应的数据
        for (Long key : ManageConnections.channelList.keySet()) {
            if (ManageConnections.channelList.get(key) == ctx.channel()) {
                //断开连接后，数据库表`ip_and_port`的对应的ip的is_connected改为0

                IpAndPort ipAndPort = new IpAndPort();
                ipAndPort.setAquariumId(key);
                ipAndPort.setIsConnected(0);
                log.info("断开连接ip：",ipAndPort);
                ipAndPortService.updateById(ipAndPort);

                //集合中删除这个通道信息
                ManageConnections.channelList.remove(key);
            }
        }


        super.channelInactive(ctx);
    }

    //异常发生
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        //根据异常的channel删除map中对应的数据
        for (Long key : ManageConnections.channelList.keySet()) {
            if (ManageConnections.channelList.get(key) == ctx.channel()) {
                //断开连接后，数据库表`ip_and_port`的对应的ip的is_connected改为0
                IpAndPort ipAndPort = new IpAndPort();
                ipAndPort.setAquariumId(key);
                ipAndPort.setIsConnected(0);
                ipAndPortService.updateById(ipAndPort);

                //集合中删除这个通道信息
                ManageConnections.channelList.remove(key);
                System.out.println("异常处理执行");
            }
        }
        cause.printStackTrace();
        ctx.close();
    }
}
